package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 分片广播任务
 *
 * @author xuxueli 2017-07-25 20:56:50
 */
@JobHandler(value = "shardingJobHandler")
@Component
public class ShardingJobHandler extends IJobHandler {

    private static List<Long> userIds = new ArrayList<>();

    static {
        userIds.add(1001L);
        userIds.add(1002L);
        userIds.add(1003L);
        userIds.add(1004L);
        userIds.add(1005L);
    }

    @Override
    public ReturnT<String> execute(String param) throws Exception {

        // 分片参数
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        XxlJobLogger.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardingVO.getIndex(), shardingVO.getTotal());
        System.out.println("分片广播任务执行: " + shardingVO.getIndex() + "/" + shardingVO.getTotal());
        for (Long userId : userIds) {
          if(userId%shardingVO.getTotal()==shardingVO.getIndex()){
              System.out.println("分片参数匹配到了对应的userId"+ userId);
          }
        }
        // 业务逻辑
        for (int i = 0; i < shardingVO.getTotal(); i++) {
            if (i == shardingVO.getIndex()) {
                XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
            } else {
                XxlJobLogger.log("第 {} 片, 忽略", i);
            }
        }

        return SUCCESS;
    }

}
